package cn.iocoder.yudao.module.esim.dal.redis.esasset;

import cn.iocoder.yudao.module.esim.dal.redis.RedisKeyConstants;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

/**
 * Description:
 * Author: li
 * Date: 2024/3/2
 */
@Repository
public class EsAssetLockRedisDAO {
    @Resource
    private RedissonClient redissonClient;

    public <T> T lockOrder(String orderNo, Long timeoutMillis, Callable<T> callable) {
        String lockKey = formatOrderKey(orderNo);
        RLock lock = redissonClient.getLock(lockKey);
        try {
            lock.lock(timeoutMillis, TimeUnit.MILLISECONDS);
            // 执行逻辑
            return callable.call();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

    private static String formatOrderKey(String orderNo) {
        return String.format(RedisKeyConstants.ESIM_CREATE_ASSET_ORDER_LOCK, orderNo);
    }

    public <T> T lockUserWhenActive(Long userId, Long timeoutMillis, Callable<T> callable) {
        String lockKey = formatActiveAssetUserKey(userId);
        RLock lock = redissonClient.getLock(lockKey);
        try {
            lock.lock(timeoutMillis, TimeUnit.MILLISECONDS);
            // 执行逻辑
            return callable.call();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

    private static String formatActiveAssetUserKey(Long userId) {
        return String.format(RedisKeyConstants.ESIM_ACTIVE_ASSET_USER_LOCK, userId);
    }
}
